<?php

class AutocompleteController extends Controller
{

    public function actionCategory()
    {
	$q = Yii::app()->request->getParam('q');
	$limit = Yii::app()->request->getParam('limit', 10);
	if ($q == 'alltop') {
	    $categories = FactoryService::get('category')->getList(array('limit' => $limit, 'order' => 'sort DESC'));	    
	    echo CJSON::encode($this->_toAutocomplete($categories));
	}
	elseif (!empty($q)) {
	    $categories = FactoryService::get('category')->getAll(array('limit' => $limit, 'order' => 'sort DESC', 'where' => '`title` LIKE \'' . CHtml::encode($q) . '%\''));	    
	    echo CJSON::encode($this->_toAutocomplete($categories));
	}
	Yii::app()->end();
    }
    protected function _toAutocomplete($categories)
    {
	if (empty($categories)) {
	    return array();
	}
	$data = array();
	foreach($categories as $category) {
	    $data[] = (array)$category->getDbData();
	}
	return $data;
    }

}